package com.bw.eurekamongodb.service;


import com.bw.common.dto.LogDto;
import com.bw.common.vo.ResultVO;
import com.bw.eurekamongodb.entity.LogEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogService {


    @Autowired
    MongoTemplate mongoTemplate;


    public ResultVO findLogPage(LogDto logDto){
        Query query = new Query();
        if (StringUtils.isNotBlank(logDto.getHost())){
            query.addCriteria(Criteria.where("host").is(logDto.getHost()));
        }
        if (StringUtils.isNotBlank(logDto.getMethodName())){
            query.addCriteria(Criteria.where("methodName").regex(logDto.getMethodName()));
        }
        long count = mongoTemplate.count(query, LogEntity.class);
        query.skip((logDto.getPageNO()-1)*logDto.getPageSize());
        query.limit(logDto.getPageSize());
        List<LogEntity> logEntities = mongoTemplate.find(query, LogEntity.class);
        Map<String,Object> map = new HashMap<>();
        map.put("total",count);
        map.put("list",logEntities);
        return ResultVO.success(map);
    }


    public void saveLog(LogEntity logEntity){
        mongoTemplate.save(logEntity);
    }
}
